package com.controller;

import com.alibaba.fastjson.JSON;
import com.dto.FreeRoomDTO;
import com.dto.MeetingDTO;
import com.dto.MeetingViewDTO;
import com.pojo.Attendee;
import com.pojo.Meeting;
import com.pojo.Room;
import com.pojo.User;
import com.service.AttendeeService;
import com.service.MeetingService;
import com.service.RoomService;
import com.service.UserService;
import com.utils.Constants;
import com.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


@Controller
public class MeetingController {

    @Autowired
    private MeetingService meetingService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private AttendeeService attendeeService;

    @RequestMapping("/meeting/apply1.html")
    public String toApply1(@RequestParam(value = "queryDate",required = false) java.sql.Date queryDate,
                           @RequestParam(value = "pageIndex",required = false) Integer pageIndex,
                           Model model){
        if (queryDate!=null){

            if(pageIndex==null||pageIndex<1) {
                pageIndex=1;
            }

            int totalCount = meetingService.getFreeRoomCount(queryDate);
            PageSupport pages=new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(Constants.pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount=pages.getTotalPageCount();
            System.out.println(totalPageCount);
            if(pageIndex>totalPageCount) {
                pageIndex=totalPageCount;
            }

            List<FreeRoomDTO> freeRoomDTOS = meetingService.findFreeRoom(queryDate,pageIndex);
            model.addAttribute("roomList",freeRoomDTOS);
            model.addAttribute("queryDate",queryDate);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("pageIndex",pageIndex);
        }

        return "meeting/apply1";
    }

    @GetMapping("/meeting/apply2/{rid}/{useDate}/{useTime}")
    public String toApply2(@PathVariable("rid") Integer rid,
                           @PathVariable("useDate") java.sql.Date useDate,
                           @PathVariable("useTime") Integer useTime,
                           Model model){
        Meeting meeting = new Meeting();
        meeting.setRoomid(rid);
        meeting.setUsedate(useDate);
        meeting.setUsetime(useTime);

        List<User> useList1 = attendeeService.getStaffList();
        //List<User> useList2 = userService.findUserList(null,null,2,null,null,null);


        model.addAttribute("userlist1",useList1);
       // model.addAttribute("userlist2",useList2);

        model.addAttribute("meeting",meeting);

        return "meeting/apply2";
    }

    @PostMapping("/meeting/save.html")
    public String doApply1(@Valid Meeting meeting,
                           BindingResult bindingResult,
                           @RequestParam(value = "aids",required = false) List<Integer> aids,
                           HttpSession session,
                           Model model){
        System.out.println(meeting);
        if (bindingResult.hasErrors()){
            List<User> useList1 = attendeeService.getStaffList();
            //List<User> useList2 = userService.findUserList(null,null,2,null,null,null);


            model.addAttribute("userlist1",useList1);
            return "meeting/apply2";
        }

        Integer id = ((User) session.getAttribute("userSession")).getId();
        meeting.setApplicantid(id);
        meeting.setApplicantdate(new Date());
        boolean res = meetingService.applySave(meeting,aids);;
        if (res){
            return "redirect:/meeting/applylist.html";
        }

        return "meeting/apply2";
    }

    @RequestMapping("/meeting/applylist.html")
    public String list(Model model,
                       @RequestParam(value="queryMeetingStatus",required=false) String queryMeetingStatus,
                       @RequestParam(value="pageIndex",required=false) Integer pageIndex,
                       HttpSession session){

        System.out.println(queryMeetingStatus);
        System.out.println(pageIndex);
        int pageSize=5;
        if(pageIndex==null||pageIndex<1) {
            pageIndex=1;
        }

        Integer uid = ((User)session.getAttribute("userSession")).getId();

        // 符合条件的总数量
        int totalCount=meetingService.getMeetingCount(queryMeetingStatus,uid);
        System.out.println("totalCount="+totalCount);

        // 分页控制
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(pageIndex);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount=pages.getTotalPageCount();
        System.out.println(totalPageCount);
        if(pageIndex>totalPageCount) {
            pageIndex=totalPageCount;
        }
        System.out.println(pageIndex);
        // 获取会议列表

        List<MeetingDTO> MeetDTOList=meetingService.getMeetingList(queryMeetingStatus,uid,(pageIndex-1)*pageSize, pageSize);
        model.addAttribute("meetList",MeetDTOList);
        MeetDTOList.forEach(System.out::println);


        model.addAttribute("queryMeetingStatus",queryMeetingStatus);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("pageIndex",pageIndex);

        return "/meeting/list";


    }

    @RequestMapping("/meeting/approvallist.html")
    public String approvalList(Model model,
                       @RequestParam(value="queryMeetingStatus",required=false) String queryMeetingStatus,
                       @RequestParam(value="pageIndex",required=false) Integer pageIndex){

        System.out.println(queryMeetingStatus);

        int pageSize=5;
        if(pageIndex==null||pageIndex<1) {
            pageIndex=1;
        }


        // 符合条件的总数量
        int totalCount=meetingService.getApprovalCount(queryMeetingStatus);
        System.out.println("totalCount="+totalCount);

        // 分页控制
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(pageIndex);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount=pages.getTotalPageCount();
        if(pageIndex>totalPageCount) {
            pageIndex=totalPageCount;
        }

        // 获取用户列表
        List<MeetingDTO> MeetDTOList=meetingService.getApprovalList(queryMeetingStatus,(pageIndex-1)*pageSize, pageSize);
        model.addAttribute("meetList",MeetDTOList);
        MeetDTOList.forEach(System.out::println);


        model.addAttribute("queryMeetingStatus",queryMeetingStatus);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("pageIndex",pageIndex);

        return "/approve/list";


    }

    @GetMapping(value="/meeting/view/{mid}")
    public String viewMeeting(@PathVariable Integer mid, Model model) {
        MeetingViewDTO meetingViewDTO = meetingService.getMeetingById(mid);
        model.addAttribute("meeting", meetingViewDTO);
        return "/meeting/view";
    }


    @RequestMapping(value="/meeting/updateStatus.html/{mid}/{status}")
    public String doUpdateMeetStatus(@PathVariable("mid") Integer mid,
                                     @PathVariable("status") String status,
                                     HttpSession session) {
        String url = null;
        Meeting meeting = new Meeting();
        meeting.setId(mid);
        if ("3".equals(status) || "4".equals(status)){
            meeting.setApprovalid(((User)session.getAttribute("userSession")).getId());
            meeting.setApprovaldate(new Date());
            url = "redirect:/meeting/approvallist.html";
        } else {
            url = "redirect:/meeting/applylist.html";
        }
        meeting.setStatus(status);
        boolean val=meetingService.updateMeeting(meeting);
        if(val) {
            System.out.println("success");
            // 成功：转跳用户列表页面

        } else {
            System.out.println("failure");
        }

        System.out.println(url);
        // 失败：返回添加用户页面
        return url;
    }

    @RequestMapping(value="/meeting/updateCheckStatus.html/{mid}/{checkStatus}")
    public String doUpdateMeetCheckStatus(@PathVariable("mid") Integer mid,
                                     @PathVariable("checkStatus") String checkStatus) {

        Meeting meeting = new Meeting();
        meeting.setId(mid);
        meeting.setCheckstatus(checkStatus);

        boolean val=meetingService.updateMeeting(meeting);
        if(val) {
            System.out.println("success");
            // 成功：转跳用户列表页面

        }
        System.out.println("failure");
        // 失败：返回添加用户页面
        return "redirect:/meeting/applylist.html";
    }

    @RequestMapping("/meeting/delete.html")
    @ResponseBody
    public String delete(Integer mid){

        HashMap<String,String> map = new HashMap<String, String>();

        MeetingViewDTO meeting = meetingService.getMeetingById(mid);
        if(meeting!=null){
            try {
                meetingService.deleteMeetingById(mid);
                System.out.println("您成功删除了"+meeting);
                map.put("delResult","true");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("您没能删除"+meeting);
                map.put("delResult","false");
            }
        }else {
            System.out.println("该会议室不存在");
            map.put("deResulte","notexist");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/meeting/upload")
    public String toUpload(Integer mid,Model model){
        model.addAttribute("mid",mid);
        return "/meeting/upload";
    }

    @PostMapping("/meeting/upload")
    public String fileUpload(@RequestParam(value="a_file",required=false ) MultipartFile attach,
                             @RequestParam("mid") Integer mid,
                             HttpServletRequest request,
                             HttpSession session) throws IOException {
        String idPicPath=null;
        //如果文件为空，直接回到首页！
        if (attach.isEmpty()){
            return "redirect:/meeting/applylist.html";
        }
        String std_prefix=".png.jpg.jpeg.gif";
        long std_filesize=500000;
        // 获取上传文件及相关信息
        String oldFilename=attach.getOriginalFilename();// 1.docx
        long fileSize = attach.getSize();
        String prefix= FilenameUtils.getExtension(oldFilename);//docx

        if(fileSize>std_filesize) {
            request.setAttribute("uploadError", "上传文件大小不得超过4M");
            return "user/useradd";
        }else if( std_prefix.contains(prefix.toLowerCase())==false) {
            request.setAttribute("uploadError", "上传文件必须是png，jpg，gif");
            return "user/useradd";
        }

        // 明确文件存放位置及策略
        String relativePath = "statics\\uploadfiles\\";
        int hashCode = oldFilename.hashCode();
        System.out.println(hashCode);
        int dir1 = hashCode& 0x0f;
        int dir2 = hashCode& 0xf0;
        String newPath=relativePath+dir1+File.separator+dir2;
        String savaPath = session.getServletContext().getRealPath(newPath);
        System.out.println(savaPath);

        String newFilename = UUID.randomUUID().toString()+"."+prefix;

        File targetFile = new File(savaPath,newFilename);
        if(targetFile.exists()==false) {
            System.out.println("123");
            targetFile.mkdirs();
        }

        try {
            attach.transferTo(targetFile);
        } catch (Exception e) {
            request.setAttribute("uploadError", "上传文件失败");
            e.printStackTrace();
            return "/meeting/upload";
        }
        idPicPath = newPath+File.separator+newFilename;
        Meeting meeting = new Meeting();
        meeting.setId(mid);
        meeting.setSummaryurl(idPicPath);
        meetingService.updateMeeting(meeting);
        return "redirect:/meeting/updateCheckStatus.html/"+mid+"/4";
    }

    @RequestMapping(value="/meeting/download/{mid}")
    public String downloads(HttpServletResponse response ,
                            @PathVariable Integer mid,
                            HttpServletRequest request) throws Exception{
        MeetingViewDTO meeting = meetingService.getMeetingById(mid);
        String url = meeting.getSummaryUrl();

        //要下载的图片地址
        String  path = request.getServletContext().getRealPath(url);
        String  fileName = "会议摘要.jpg";

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path);
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return "redirect:/meeting/applylist.html";
    }
}
